{% extends "layout/enter.html" %}

{% block title %}忘记密码{% endblock  %}

{% block content %}

<main class="w-100 m-auto">
    <form id="regForm" method="post" style="width: 400px; margin: 0 auto">
        {% csrf_token %}
        <h1 class="h3 mb-3 fw-normal" style="text-align: center;">账户重置</h1>

        <div class="form-floating" style="margin:20px 0">
            {{ form.usermail }}
            <label for="floatingInput">邮箱</label>
            <div class="text-danger" id="id_error" style="margin-left: 4px;position: absolute;font-size: 14px;">
                {{form.usermail.errors.0 }}</div>
        </div>

        <div class="form-floating" style="margin:20px 0; position: relative;">
            {{ form.code }}
            <label for="floatingInput">邮箱验证码</label>
            <div class="text-danger" style="margin-left: 4px;position: absolute;font-size: 14px;">{{ form.code.errors.0 }}</div>
            <button type="button" id="send-code-btn" class="btn btn-success"
                style="position: absolute; right: 10px; top: 13px; font-size: 13px; background-color: #51A473;border: 0;">
                发送验证码
            </button>
            <div id="code-message" class="text-success" style="font-size: 12px; margin-top: 5px;"></div>
        </div>

        <div class="form-floating" style="margin:20px 0">
            {{ form.password }}
            <label for="floatingPassword">修改密码</label>
            <div class="text-danger" style="margin-left: 4px;position: absolute;font-size: 14px;">{{ form.password.errors.0 }}</div>
        </div>

        <div class="form-floating" style="margin:20px 0">
            {{ form.confirm_password }}
            <label for="floatingPassword">确认密码</label>
            <div class="text-danger" style="margin-left: 4px;position: absolute;font-size: 14px;">{{ form.confirm_password.errors.0 }}</div>
        </div>

        <div class="form-check text-start my-3" style="padding-left: 0;">
            <span style="float: left;">
                没有账户?<a href="/register/">前往注册</a>
            </span>
            <span style="float: right;">
                已有账户?前往<a href="/login/">登录</a>
            </span>
        </div>

        <input class="btn btn-primary w-100 py-2" id="btmSubmit" type="button" value="重置密码"></input>
        <p class="mt-5 mb-3 text-body-secondary">&copy; 2025</p>
    </form>
</main>
{% endblock  %}

<!-- jQuery -->
{% block js %}
<script>
    // 页面加载时立即执行
    $(function () {
        bindSendCodeBtn();
        restoreCountdown(); // 关键修复：页面加载时检查并恢复倒计时
        bindClickSubmit();
    });
    // 点击注册
    $(function() {
        $('#btmSubmit').click(function() {
            // 点击注册清空错误信息
            $('.text-danger').empty()
            // 收集表单中的数据
            $('#regForm').serialize() // 表单中所有字段数据 + csrf_token

            // 数据ajax发送到后台
            $.ajax({
                url:'/forgot/password/',
                type: "POST",
                data: $('#regForm').serialize(),
                dataType:"JSON",
                success: function(res) {
                    if (res.status){
                        // 显示注册成功提示
                       showNotification('修改密码成功，正在跳转...', 'success');
                        // 延迟2秒后跳转
                        setTimeout(function() {
                            location.href = res.data;
                        }, 2000);
                            
                    }else{
                        $.each(res.error, function(key, value) {
                            $("#id_" + key).next().next().text(value[0])
                        })
                    }
                }

            })
        })
    })

    // 绑定发送验证码按钮
    function bindSendCodeBtn() {
        $('#send-code-btn').click(function () {
            const userMail = $('#id_usermail').val().trim();

            // 1. 输入验证
            if (!userMail) {
                showNotification("请输入邮箱地址", "error");
                return;
            }
            if (!isValidEmail(userMail)) {
                showNotification("邮箱格式不正确", "error");
                return;
            }

            // 2. 发送AJAX请求
            $.ajax({
                url: '/send/email_code/forget/',
                type: "GET",
                data: { usermail: userMail },
                success: function (res) {
                    console.log(res)
                    if (res.status) {
                        showNotification("验证码已发送！", "success");
                        startCountdown(); // 开始新倒计时
                    } else {
                        showNotification(res.message || "发送失败", "error");
                    }
                },
                error: function () {
                    showNotification("网络错误", "error");
                }
            });
        });
    }

    // 🚨 关键修复：恢复倒计时
    function restoreCountdown() {
        const endTime = parseInt(localStorage.getItem('countdownEndTime'));

        // 检查是否有未完成的倒计时
        if (endTime) {
            const now = Date.now();
            const remainingMs = endTime - now;

            // 如果倒计时未结束
            if (remainingMs > 0) {
                const remainingSeconds = Math.ceil(remainingMs / 1000);
                startCountdown(remainingSeconds); // 从剩余时间继续
            } else {
                localStorage.removeItem('countdownEndTime');
            }
        }
    }

    // 启动/恢复倒计时
    function startCountdown(seconds = 60) {
        const $btn = $('#send-code-btn');

        // 1. 存储精确的倒计时结束时间戳
        const endTime = Date.now() + seconds * 1000;
        localStorage.setItem('countdownEndTime', endTime.toString());

        // 2. 立即更新按钮状态
        updateButton(seconds);

        // 3. 启动计时器
        const timer = setInterval(() => {
            seconds--;
            updateButton(seconds);

            // 倒计时结束
            if (seconds <= 0) {
                clearInterval(timer);
                localStorage.removeItem('countdownEndTime');
                resetButton();
            }
        }, 1000);

        // 页面关闭时清除定时器
        $(window).on('beforeunload', () => clearInterval(timer));
    }

    // 更新按钮状态
    function updateButton(seconds) {
        $('#send-code-btn')
            .prop('disabled', true)
            .css({
                'background-color': '#ccc',
                'cursor': 'not-allowed'
            })
            .text(`${seconds}秒后重试`);
    }

    // 重置按钮状态
    function resetButton() {
        $('#send-code-btn')
            .prop('disabled', false)
            .css({
                'background-color': '#51A473',
                'cursor': 'pointer'
            })
            .text('获取验证码');
    }

    // 显示通知
    function showNotification(message, type) {
        const $note = $('<div>')
            .css({
                'position': 'fixed',
                'top': '20px',
                'left': '50%',
                'transform': 'translateX(-50%)',
                'padding': '10px 20px',
                'background-color': type === 'success' ? '#51A473' : '#dc3545',
                'color': 'white',
                'border-radius': '4px',
                'z-index': 9999
            })
            .text(message)
            .appendTo('body')
            .delay(3000)
            .fadeOut(() => $(this).remove());
    }

    // 邮箱验证
    function isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }
</script>
{% endblock %}

